<?php

namespace app\controller;

use app\BaseController;
use think\Request;
use think\facade\Db;
use think\facade\Log;
use think\response\Json;
use app\controller\Response\TradeWechatJsapiPayResponse;
use AlipayTradePrecreateRequest;
use AopClient;
use GuzzleHttp\Client;
use Throwable;

class Notify extends BaseController
{

    //鸿闻pay退款回调
    public function refund_notify_zzj(Request $request): string
    {
        try {
            //开启事务
            Db::startTrans();

            $all = $request->all();
            log::write('退款回调1' . json_encode($all));

            //下面是收到的回调$all
            //{"notify_time":"2025-05-10 15:16:06","notify_type":"trade.refund.notify","sign_type":"RSA","refund_order_id":"779726007402659840","trade_no":"779718833456709632","out_trade_no":"779718831312277504","out_trade_refund_no":"202505101512468905","refund_status":"REFUND_SUCCESS","refund_amount":"15.00","succeed_time":"1746861172","failed_time":"0","mch_no":"23607041869916","sign":"etw3tZaeQWa0JaBXc+2cwlUmIrnqjP74yVYR4iWk5jqHmPCMdxEmSIGDEyxriBu9yqm6Vq8ERRVlMrbEfZTrXLGd4nHv0rlAefv0b1o6pdEsfEgvoZ\/8O6KXH0lkLwNT8x8HXa3vxeqw\/EXoEPyc8cubk7UaEObw37YIa63du6yfkhiJR6+dT1tfG+wyEj0GLUu9ijg+xJPBh93hQDhevWBhJCgX5EEj8E30qnDJWmCOO9LSVIiZx0MJsg0SFLO7+L9ZN6GzI9YL8M1Wy9C6D5lyJe6t4ustT43gNJOonsfr\/8qjPxabs2gP9xRdgRAZBI47fC8Jwn6lzvjVIrA61A=="}
            $res = Db::name("trade_order")->where('trade_no', $all['trade_no'])->find();
            if (!$res) {
                return 'fail';
            }
            //已经退款的订单不处理
            if ($res['refund_status'] == 'REFUND_SUCCESS') {  //当再次申请退款的时候, 此状态会再次变动
                return 'success';
            }
            //判断退款状态, 如果是退款成功
            if ($all['refund_status'] == 'REFUND_SUCCESS') {
                //退款金额等于 曾经已退款金额 + 当前的退款金额
                $refund_amount = $res['refund_amount']+$all['refund_amount'];

                Db::name("trade_order")->where('trade_no', $all['trade_no'])->update(['status' => "REFUNDED",'refund_status' => $all['refund_status'], 'refunded_at' => date('Y-m-d H:i:s', $all['succeed_time']) ?? '', "refund_amount" => $refund_amount]);
                if ($res['type'] == "GAME"){
                    Db::name("game_library")->where('user_id', $res['user_id'])->where('product_id', $res['product_id'])->where('sku_id', $res['sku_id'])->delete();
                }elseif ($res['type'] == "VIP"){
                    Db::name("vip_user")->where('user_id', $res['user_id'])->update(['type' => 'TIME_LIMITED', 'status' => 'EXPIRED', 'expired_at' => date('Y-m-d H:i:s')]);
                }
            }
            //提交事务
            Db::commit();
            return 'success';

        } catch (\Exception $e) {
            var_dump($e->getMessage());
            // 回滚事务
            Db::rollback();
            return 'fail';
        }
    }




}
